import {createRouter, createWebHistory} from 'vue-router'
import {useTokenStore} from '@/stores/token.js'

//导入组件
import LoginVue from '@/views/Login.vue'
import LayoutVue from '@/views/Layout.vue'

import BookManageVue from '@/views/book/BookManage.vue'
import BookRecordVue from '@/views/book/BookRecord.vue'
import UserAvatarVue from '@/views/user/UserAvatar.vue'
import UserInfoVue from '@/views/user/UserInfo.vue'
import UserResetPasswordVue from '@/views/user/UserResetPassword.vue'
import UserAdminVue from '@/views/user/UserAdmin.vue'

//定义路由关系
const routes = [
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/user/Login.vue'),
        meta: {
            title: '登录/注册',
            requiresAuth: false
        }
    },
    {
        path: '/', 
        component: LayoutVue, 
        redirect: '/login', 
        meta: { requiresAuth: true },
        children: [
            {path: '/book/manage', component: BookManageVue},
            {path: '/book/record', component: BookRecordVue},
            {path: '/user/info', component: UserInfoVue},
            {path: '/user/avatar', component: UserAvatarVue},
            {path: '/user/resetPassword', component: UserResetPasswordVue},
            {path: '/user/admin', component: UserAdminVue}
        ]
    }
]

//创建路由器
const router = createRouter({
    history: createWebHistory(),
    routes: routes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
    const tokenStore = useTokenStore()
    const token = tokenStore.token
    
    // 设置页面标题
    if (to.meta.title) {
        document.title = to.meta.title
    }

    // 需要登录但没有token，重定向到登录页
    if (to.meta.requiresAuth && !token) {
        next({ name: 'Login' })
    } else {
        next()
    }
})

//导出路由
export default router
